<?php

namespace app\http\controller\admin\sys;

use mon\util\File;
use mon\env\Config;
use mon\util\UploadFile;
use mon\util\exception\UploadException;
use app\http\controller\admin\Controller;

/**
 * 文件管理
 */
class FileManageController extends Controller
{
    /**
     * 配置信息
     *
     * @var array
     */
    protected $setting = [];

    /**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();
        $this->setting = Config::instance()->get('admin.fileSys', []);
        if (!isset($this->setting['enable']) || !$this->setting['enable']) {
            return $this->error('未启用文件管理系统');
        }
    }

    /**
     * 查看
     *
     * @return void
     */
    public function index()
    {
        // 查询目录内容
        if ($this->request->isPost()) {
            return $this->query();
        }
        $setting = $this->setting;
        $setting['rename'] = $this->auth->check('/admin/sys/filemanage/rename', $this->userInfo['id']);
        $setting['del'] = $this->auth->check('/admin/sys/filemanage/del', $this->userInfo['id']);
        $this->assign('setting', json_encode($setting, JSON_UNESCAPED_UNICODE));
        return $this->fetch('sys/filemanage');
    }

    /**
     * 获取目录内容
     *
     * @return void
     */
    public function query()
    {
        $path = $this->request->post('path', $this->setting['root']);
        // 验证合法路径
        if (strpos($path, $this->setting['root']) !== 0 || strpos($path, '..') !== false) {
            return $this->error('访问路径不合法');
        }
        $info = File::instance()->getDirContent($path);
        $info = array2DSort($info, 'is_dir');
        return $this->success('ok', $info);
    }

    /**
     * 创建目录
     *
     * @return void
     */
    public function mkdir()
    {
        $path = $this->request->post('path', $this->setting['root']);
        // 验证合法路径
        if (strpos($path, $this->setting['root']) !== 0 || strpos($path, '..') !== false) {
            return $this->error('访问路径不合法');
        }

        if (is_dir($path)) {
            return $this->error('目录已存在');
        }

        $create = File::instance()->createDir($path);
        if (!$create) {
            return $this->error('创建目录失败(' . $path . ')');
        }

        return $this->success('创建目录成功');
    }

    /**
     * 文件上传
     *
     * @return string
     */
    public function upload(UploadFile $sdk)
    {
        $saveDir = $this->request->post('path', $this->setting['root']);
        // 验证合法路径
        if (strpos($saveDir, $this->setting['root']) !== 0 || strpos($saveDir, '..') !== false) {
            return $this->error('路径不合法');
        }
        if (!is_dir($saveDir)) {
            $createDir = File::instance()->createDir($saveDir);
            if (!$createDir) {
                return $this->dataReturn(0, '创建存储目录失败，请检查写入权限：' . $saveDir);
            }
        }
        $sdk->rootPath = $saveDir . DIRECTORY_SEPARATOR;
        $sdk->maxSize = $this->setting['maxSize'];
        $sdk->exts = $this->setting['exts'];
        try {
            $sdk->upload()->save()->getFile();
            return $this->dataReturn(1, 'ok');
        } catch (UploadException $e) {
            return $this->dataReturn(0, $e->getMessage());
        }
    }

    /**
     * 删除
     *
     * @return void
     */
    public function del()
    {
        $path = $this->request->post('path');
        if (is_array($path)) {
            // 数组，批量删除
            foreach ($path as $item) {
                $rm = $this->remove($item);
                if ($rm !== true) {
                    return $this->error($rm);
                }
            }
        } else {
            $rm = $this->remove($path);
            if ($rm !== true) {
                return $this->error($rm);
            }
        }

        return $this->success('删除成功');
    }

    /**
     * 删除文件目录实体方法
     *
     * @param string $path  文件目录路径
     * @return mixed
     */
    protected function remove($path)
    {
        // 验证合法路径
        if (strpos($path, $this->setting['root']) !== 0 || strpos($path, '..') !== false) {
            return '路径不合法';
        }
        // 删除文件
        if (is_file($path)) {
            $del = File::instance()->removeFile($path);
            if ($del === false) {
                return '删除文件失败';
            }
        } else if (is_dir($path)) {
            $del = File::instance()->removeDir($path, true);
            if ($del === false) {
                return '删除目录失败';
            }
        }

        return true;
    }

    /**
     * 重命名
     *
     * @return void
     */
    public function rename()
    {
        $path = $this->request->post('path');
        // 验证合法路径
        if (strpos($path, $this->setting['root']) !== 0 || strpos($path, '..') !== false) {
            return $this->error('路径不合法');
        }
        $oldname = $this->request->post('oldname');
        $newname = $this->request->post('newname');
        if (!$oldname || !$newname) {
            return $this->error('参数异常，未指定文件目录名称');
        }
        $oldFile = $path . DIRECTORY_SEPARATOR . $oldname;
        $newFile = $path . DIRECTORY_SEPARATOR . $newname;
        if (!file_exists($oldFile)) {
            return $this->error('原文件目录不存在');
        }
        if (file_exists($newFile)) {
            return $this->error('新文件目录已存在');
        }

        $rename = File::instance()->rename($oldFile, $newFile);
        if (!$rename) {
            return $this->error('重命名失败');
        }

        return $this->success('重命名成功');
    }
}
